<template>
  <el-card class="box-card">
    <el-breadcrumb separator="/" style="margin-bottom: 20px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图管理</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="swiperListQuery" class="demo-form-inline">
      <el-form-item label="跳转链接">
        <el-input
          v-model="swiperListQuery.link"
          placeholder="请输入跳转链接"
          clearable
          size="large"
        />
      </el-form-item>
      <el-form-item label="图片alt">
        <el-input
          v-model="swiperListQuery.alt"
          placeholder="请输入图片alt"
          clearable
          size="large"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="clear">清空</el-button>
        <el-button type="primary" @click="getSwiperListData">搜索</el-button>
        <el-button type="success" @click="dialogVisible = true"
          >+新增轮播图</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 轮播图列表表格 -->

  <el-card style="margin-top: 20px">
    <el-table :data="swiperList" style="width: 100%">
      <el-table-column prop="img" label="轮播图图片">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.img"
            :preview-src-list="[scope.row.img]"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="link" label="跳转地址">
        <template #default="scope">
          <a :href="scope.row.link" target="_blank">{{ scope.row.link }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="alt" label="轮播图alt" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-switch
            :modelValue="scope.row.flag"
            :active-value="true"
            :inactive-value="false"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="edit(scope.row)">修改</el-button>
          <el-button type="danger" @click="delSwiper(scope.row.bannerid)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="swiperListQuery.page"
      v-model:page-size="swiperListQuery.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="getSwiperListData"
      @current-change="getSwiperListData"
      class="paginationn"
    />
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="mode === 'add' ? '新增轮播图' : '修改轮播图'"
    @close="close"
  >
    <el-form
      ref="ruleFormRef"
      :model="swiperDialogInfo"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="图片" prop="img">
        <el-upload
          class="avatar-uploader"
          :action="action"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <div class="uploadBox" v-if="swiperDialogInfo.img">
            <div class="mask">
              <el-icon size="20px" @click.stop="reset"
                ><i-ep-Delete class="Delicon"
              /></el-icon>
            </div>

            <img :src="swiperDialogInfo.img" class="upload-avatar" />
          </div>
          <div class="addupload" v-else>
            <el-icon class="avatar-uploader-icon" size="80px"
              ><i-ep-Plus class="plus-icon"
            /></el-icon>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="跳转链接" prop="link">
        <el-input v-model="swiperDialogInfo.link" />
      </el-form-item>
      <el-form-item label="alt说明" prop="alt">
        <el-input v-model="swiperDialogInfo.alt" />
      </el-form-item>
      <el-form-item label="启用/禁用">
        <el-switch
          v-model="swiperDialogInfo.flag"
          :active-value="true"
          :inactive-value="false"
        ></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onsumbit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { SwiperQuery, SwiperData } from '@/types/swiper'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getSwiper,
  getAddSwiperData,
  updateSwiper,
  deleteSwiper
} from '@/api/swiper'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps } from 'element-plus'
// 图片上传服务器地址
const action = ref(import.meta.env.VITE_BASE_URL + 'file/upload')

// 轮播图查询列表数据
const swiperListQuery = ref({
  link: '',
  alt: '',
  page: 1,
  pageSize: 2
} as SwiperQuery)

// 弹窗
const dialogVisible = ref(false)
// 模态值，控制修改弹窗标题

const mode = ref<'add' | 'edit'>('add')

// 轮播图数据总条数
const total = ref(0)
// 轮播图列表数据
const swiperList = ref([] as SwiperData[])

//表单项
const ruleFormRef = ref<FormInstance>()
const swiperDialogInfo = ref<SwiperData>({
  img: '',
  alt: '',
  banneid: '',
  flag: true,
  link: ''
})

// 表单校验规则
const rules = reactive<FormRules<SwiperData>>({
  img: [{ required: true, message: '请上传图片', trigger: 'blur' }],
  link: [{ required: true, message: '请填写上传链接', trigger: 'blur' }]
})

// 获取轮播图数据
const getSwiperListData = async () => {
  const res = await getSwiper(swiperListQuery.value)
  swiperList.value = res.data.data.items
  total.value = res.data.data.total
}
getSwiperListData()

// 清空按钮
const clear = () => {
  swiperListQuery.value.alt = ''
  swiperListQuery.value.link = ''
  getSwiperListData()
}

// 确认按钮
const onsumbit = async () => {
  if (!ruleFormRef.value) return
  try {
    await ruleFormRef.value.validate()
    const res =
      mode.value === 'add'
        ? await getAddSwiperData(swiperDialogInfo.value)
        : await updateSwiper(swiperDialogInfo.value)
    console.log(res)

    // 提示信息
    ElMessage.success(res.data.message)
    if (mode.value === 'add') {
      swiperListQuery.value.page = 1
      getSwiperListData()
    }
    // 关闭弹窗
    dialogVisible.value = false
    getSwiperListData()
  } catch (error) {
    console.log(error)
  }
}

// 修改轮播图数据
const edit = (row: SwiperData) => {
  mode.value = 'edit'
  swiperDialogInfo.value = { ...row }
  dialogVisible.value = true
}
// 删除轮播图数据
const delSwiper = async (bannerid: string) => {
  const res = await deleteSwiper(bannerid)
  if (res.data.code === 200) {
    ElMessageBox.confirm('你确定删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await deleteSwiper(bannerid)
      // 删除成功重新查询列表
      getSwiperListData()
      ElMessage.success(res.data.message)
    })
  }
}

// 弹窗关闭
const close = () => {
  mode.value = 'add'
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
    swiperDialogInfo.value = {
      img: '',
      alt: '',
      banneid: '',
      flag: true,
      link: ''
    }
  }
}

/**
 * 图片上传
 */

const handleAvatarSuccess: UploadProps['onSuccess'] = (_, uploadFile) => {
  swiperDialogInfo.value.img = URL.createObjectURL(uploadFile.raw!)
}
// 点击删除上传的图片
const reset = () => {
  swiperDialogInfo.value.img = ''
}
</script>

<style lang="scss" scoped>
.uploadBox {
  width: 140px;
  height: 140px;
  position: relative;
}
.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: none;
  position: absolute;
  left: 0;
  top: 0;
}
.uploadBox:hover .mask {
  display: block;
}
.Delicon {
  position: absolute;
  top: 65px;
  left: 65px;
}
.upload-avatar {
  width: 140px;
  height: 140px;
}
.plus-icon {
  width: 140px;
  height: 140px;
}
.paginationn {
  margin-left: 316px;
  margin-top: 20px;
}
</style>
